<!doctype html>
<head>
	<meta charset="utf-8" />
</head>
<body>


	<div> 
		<input type="file" id="langText" />
		<button id="queren">确认</button>
		<button id="queren2">翻译数据</button>
		<button id="queren3">存储数据</button>
	</div>


	<script src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
	<script src="./md52.js"></script>
	<script type="text/javascript">
		let objData = []
		let newObj = {}
		let count = 0;

		$('#queren2').click((e) => {
			
			let intervalId = setInterval(() => {
				i18nFy(objData[count].value).then(e => {
					newObj[objData[count].key1][objData[count].key2] = e;
					console.log(newObj)
					count++;
				});
				if (count == objData.length-1) {
					clearInterval(intervalId);
				}
			}, 500);

		})

		$('#queren3').click((e) => {
			
			let fileName = "cn2.js"; //文件名
			//使用 data URI 将文件内容转换为 URL 形式
			let fileContent = JSON.stringify(newObj)
			let dataUri = "data:text/javascript;charset=utf-8," + encodeURIComponent(`export default ${fileContent}`);
			//创建一个 <a> 标签，设置 href 属性为 data URI
			let downloadLink = $("<a>").attr({
				href: dataUri,
				download: fileName
			}).appendTo("body");
			//模拟点击该 <a> 标签
			downloadLink.get(0).click();
			//删除创建的 <a> 标签
			downloadLink.remove();

		})

		$('#queren').click((e) => {
			var reader = new FileReader();
			reader.onload = function(event) {
				console.log($("#langText")[0].files[0])
				let myObjaa = String(event.target.result)
				myObjaa = myObjaa.replace('export default', '')
				myObjaa = myObjaa.trim()
				// myObjaa = JSON.parse(myObjaa)
				// myObjaa = JSON.stringify(myObjaa)

				let func = new Function(`return (${myObjaa})`);
				let obj = func();

				for (item in obj) {
					newObj[item] = {}
					for (item2 in obj[item]) {
						newObj[item][item2] = ''
						let aaaa = obj[item][item2];
						objData.push({
							key1: item,
							value: obj[item][item2],
							key2: item2,
						})
					}
				}
				
				console.log(objData)

			};
			reader.readAsText($("#langText")[0].files[0]);
		})
		
		function i18nFy(Str) {
			return new Promise((resolve, reject) => {
				var appid = '20211108000993824';
				var key = 'tsqDuzlC2atualgOdZgX';
				var salt = (new Date).getTime();
				var query = String(Str);
				// 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
				var from = 'en';
				var to = 'zh';
				var str1 = appid + query + salt + key;
				var sign = MD5(str1);
				$.ajax({
					url: 'http://api.fanyi.baidu.com/api/trans/vip/translate',
					type: 'get',
					dataType: 'jsonp',
					data: {
						q: query,
						appid: appid,
						salt: salt,
						from: from,
						to: to,
						sign: sign
					},
					success: function(data) {
		
						// console.log(data.trans_result[0].dst);
						// console.log(JSON.parse(data.trans_result[0].dst));
						resolve(data.trans_result[0].dst)
		
					}
				});
			})
		}
	</script>


</body>